<template>
  <el-dialog
    title="修改"
    :visible.sync="dialogFormVisible"
    @close="closeDialog"
  >
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="form"
      label-position="left"
      label-width="90px"
      style="width: 400px; margin-left: 50px"
    >
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.username"></el-input>
      </el-form-item>

      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>

      <el-form-item label="账户余额" prop="balance">
        <el-input-number v-model="form.balance" :min="0"></el-input-number>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog"> 取消 </el-button>
      <el-button type="primary" @click="updateData()"> 提交 </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateUser } from "@/api/index";
export default {
  name: "userEdit",
  data() {
    return {
      form: {
        userId: "",
        username: "",
        phone: "",
        balance: "",
      },
      dialogFormVisible: false,
      rules: {
        username: [
          { required: true, message: "姓名必填", trigger: "blur" },
          {
            pattern: /^.{1,10}$/,
            trigger: "blur",
            message: "不能超过十个字符",
          },
        ],
        phone: [
          { required: true, messgae: "必须输入手机号", trigger: "blur" },
          {
            pattern: /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/,
            trigger: "blur",
            message: "手机号格式有误",
          },
        ],
        balance: [
          {
            required: true,
            type: "number",
            messgae: "必须输入余额",
            trigger: "blur",
          },

        ],
      },
    };
  },

  methods: {
    init(data) {
      console.log(data);
      this.dialogFormVisible = true;
      this.form.userId = data.userId;
      this.form.username = data.username;
      this.form.phone = data.phone;
      this.form.balance = data.balance;
    },

    closeDialog() {
      this.dialogFormVisible = false;
      this.$refs["dataForm"].clearValidate();
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          updateUser(this.form).then((res) => {
            if (res.success) {
              this.closeDialog();
              this.$emit('fatherMethod');
              this.$notify({
                title: "Success",
                message: "更新成功",
                type: "success",
                duration: 2000,
              });
            } else {
              this.closeDialog();
              this.$notify({
                title: "failed",
                message: res.errorMsg,
                type: "error",
                duration: 2000,
              });
            }
          });
        }
      });
    },
  },
};
</script>
